package edu.suda.xsap.controller;

import edu.suda.xsap.common.Result;
import edu.suda.xsap.dto.MemberCardDto;
import edu.suda.xsap.entity.MemberCard;
import edu.suda.xsap.service.MemberCardService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/membercard")
@Slf4j
public class MemberCardController {
    @Autowired
    private MemberCardService memberCardService;

    @GetMapping("/list")
    public Result list() {
            try {
                return Result.success(memberCardService.findAll());
            }catch
                (Exception e) {
                    log.error("获取会员卡列表失败", e);
                    return Result.failure("获取会员卡列表失败");
                }
        }

    @PostMapping("/add")
    public Result add(@RequestBody MemberCard memberCard) {
        try {
            memberCardService.save(memberCard);
            return Result.success();
        }catch
            (Exception e) {
                log.error("添加会员卡失败", e);
                return Result.failure("添加会员卡失败");
            }
    }

    @PutMapping("/update")
    public Result update(@RequestBody MemberCard memberCard) {
        try {
            memberCardService.update(memberCard);
            return Result.success();
        }catch
            (Exception e) {
                log.error("更新会员卡失败", e);
                return Result.failure("更新会员卡失败");
            }
    }

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable("id") Integer id) {
        try {
            memberCardService.delete(id);
            return Result.success();
        }catch
            (Exception e) {
                log.error("删除会员卡失败", e);
                return Result.failure("删除会员卡失败");
            }
    }

    @GetMapping("/membercard/{id}")
    public Result get(@PathVariable("id") Integer id) {
        try {
            return Result.success(memberCardService.findById(id));
        }catch
            (Exception e) {
                log.error("获取会员卡失败", e);
                return Result.failure("获取会员卡失败");
            }
    }
    @GetMapping("/membercard/name/{name}")
    public Result getByName(@PathVariable("name") String name) {
        try {
            return Result.success(memberCardService.findByName(name));
        }catch
            (Exception e) {
                log.error("获取会员卡失败", e);
                return Result.failure("获取会员卡失败");
            }
    }

    @GetMapping("/cardList")
    public ResponseEntity<List<Map<String, Object>>> getCardListStatistics() {
        List<Map<String, Object>> stats = memberCardService.getCardTypeStatistics();
        return ResponseEntity.ok(stats);
    }
}

